package com.example.medispider.utils;

import com.example.medispider.pojo.task.MedicalInstitution;
import com.example.medispider.pojo.task.Task;
import com.example.medispider.pojo.task.TaskConfig;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class YamlLoader {


    /**
     * 加载启动配置文件
     *
     * @param yamlFilePath 启动配置文件文件路径
     * @return 过滤后的 TaskConfig 对象
     */
    public static TaskConfig loadTaskConfig(String yamlFilePath) {
        TaskConfig taskConfig = new TaskConfig();
        TaskConfig tempTaskConfig;
        try {
            tempTaskConfig = new Yaml().loadAs(new FileInputStream(yamlFilePath), TaskConfig.class);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 过滤未激活的配置
        for (Task task : tempTaskConfig.getTasks()) {
            if (task.isActive()) {
                // 测试输出根目录是否存在
                String outputRootPath = task.getOutput_root_path();
                File rootDir = new File(outputRootPath);
                if (!rootDir.exists() || !rootDir.isDirectory()) {
                    throw new RuntimeException("输出根目录不存在！");
                }
                // 过滤未激活的医疗机构
                ArrayList<MedicalInstitution> medicalInstitutions = new ArrayList<>();
                for (MedicalInstitution medicalInstitution : task.getMedical_institutions()) {
                    if (medicalInstitution.isActive()) {
                        medicalInstitutions.add(medicalInstitution);
                    }
                }
                task.setMedical_institutions(medicalInstitutions);
                taskConfig.getTasks().add(task);
            }
        }
        return taskConfig;
    }


}
